package com.my.one2many;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

//启动两次，模拟两个消费者
public class ConsumerG1_2 {

    public static void main(String[] args) throws MQClientException {
        //1.谁来收(推送模式消费者，长连接，不用轮询，效率高)
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
        //2.从哪里收
        consumer.setNamesrvAddr("localhost:9876");

        //设置消费模式（同组中也能共享数据）
        consumer.setMessageModel(MessageModel.BROADCASTING);//改为广播模式

        //3.监听(订阅)哪个队列(主题)
        consumer.subscribe("topic"+TN.TOPIC_NUMBER,"*");
        //4.处理业务流程 注册监听器
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            //MessageExt表示接受到的消息
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                //模拟业务逻辑，打印消息
                for (MessageExt messageExt : list) {
                    System.out.println("messageExt:"+messageExt);
                    System.out.println("消息内容："+ new String(messageExt.getBody()));
                    System.out.println("-----------------------------------------");
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;//返回枚举类，表示接收成功
            }
        });
        //5.启动消费者
        consumer.start();//建立连接
        System.out.println("消费者G1_2启动了...");
        //6.千万别关消费者
        //consumer.shutdown();
    }
}
